package utils

import (
	"encoding/json"
	"fmt"
	"log"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"
)

//获取当前路径，比如：E:/abc/data/test
func GetCurrentPath() string {
	dir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
	return strings.Replace(dir, "\\", "/", -1)
}

//秒时间戳转时间
func UnixToStr(timeUnix int64, layout string) string {
	timeStr := time.Unix(timeUnix, 0).Format(layout)
	return timeStr
}

//时间转时间戳
func StrToUnix(timeStr, layout string) (int64, error) {
	local, err := time.LoadLocation("Asia/Shanghai") //设置时区
	if err != nil {
		return 0, err
	}
	tt, err := time.ParseInLocation(layout, timeStr, local)
	if err != nil {
		return 0, err
	}
	timeUnix := tt.Unix()
	return timeUnix, nil
}

// 纳秒时间戳转时间
func NaniUnixToStr(timeUnix int64, layout string) string {
	timeStr := time.Unix(0,timeUnix * int64(time.Millisecond)).Format(layout)
	return timeStr
}

func DefaultPrintData(obj interface{}) error {
	switch obj.(type) {
	case string:
		fmt.Println(obj)
	default:
		msg, err := Struct2JsonString(obj)
		if err != nil {
			fmt.Println(err.Error())
			return err
		}
		fmt.Println(msg)

	}
	return nil
}

func Struct2JsonString(structt interface{}) (jsonString string, err error) {
	data, err := json.Marshal(structt)
	if err != nil {
		return "", err
	}
	return string(data), nil
}

func JsonBytes2Struct(jsonBytes []byte, result interface{}) error {
	err := json.Unmarshal(jsonBytes, result)
	return err
}

func Int64ToString(arg int64) string {
	return strconv.FormatInt(arg, 10)
}

func IntToString(arg int) string {
	return strconv.Itoa(arg)
}

func StringToInt64(arg string) int64 {
	value, err := strconv.ParseInt(arg, 10, 64)
	if err != nil {
		return 0
	} else {
		return value
	}
}

func StringToInt(arg string) int {
	value, err := strconv.Atoi(arg)
	if err != nil {
		return 0
	} else {
		return value
	}
}

func BuildParams(requestPath string, params map[string]string) string {
	urlParams := url.Values{}
	for k := range params {
		urlParams.Add(k, params[k])
	}
	return requestPath + "?" + urlParams.Encode()
}


/*
 Get a iso time
  eg: 2018-03-16T18:02:48.284Z
*/
func IsoTime() string {
	utcTime := time.Now().UTC()
	iso := utcTime.String()
	isoBytes := []byte(iso)
	iso = string(isoBytes[:10]) + "T" + string(isoBytes[11:23]) + "Z"
	return iso
}

/*
 Get utc +8 -- 1540365300000 -> 2018-10-24 15:15:00 +0800 CST
*/
func LongTimeToUTC8(longTime int64) time.Time {
	timeString := Int64ToString(longTime)
	sec := timeString[0:10]
	nsec := timeString[10:len(timeString)]
	return time.Unix(StringToInt64(sec), StringToInt64(nsec))
}

func StrMillToTime(timeString string, format string, cst *time.Location) string {
	sec := timeString[0:10]
	nsec := timeString[10:len(timeString)]
	return time.Unix(StringToInt64(sec), StringToInt64(nsec)).In(cst).Format(format)
}


func NewParams() map[string]string {
	return make(map[string]string)
}